﻿$.extend($.fn.validatebox.defaults.rules, {
    projectNum: {
        validator: function(value) {
            var reg = new RegExp("^([a-z0-9_]+)-([a-z0-9_]+)-([a-z0-9_]+)-([a-z0-9_]+)$");
            return reg.test(value);
        },
        message: '请输入正确的项目编号格式(xx-xx-xx-xx)'
    },
    constructionNum: {
        validator: function(value) {
            var reg = new RegExp("^([a-z0-9_]+)-([a-z0-9_]+)-([a-z0-9_]+)$");
            return reg.test(value);
        },
        message: "请输入正确的项目编号格式(xx-xx-xx)"
    },
    projectNumAjax: {
        validator: function(value, params) {
            var reg = new RegExp("^([a-z0-9_]+)-([a-z0-9_]+)-([a-z0-9_]+)-([a-z0-9_]+)$");
            var bl = reg.test(value);
            if (!bl) {
                $.fn.validatebox.defaults.rules.projectNumAjax.message = '请输入正确的项目编号格式(xx-xx-xx-xx)';
                return bl;
            }
            var param = { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ProjectInfoPresenter", Method: "IsExit", Options: {} };
            if (params != null && params != "undefined")
                param.Options["InternalType"] = params[0]; //工程,集成,科研 区分 默认工程
            else {
                param.Options["InternalType"] = "0";
            }
            param.Options["ProjectNum"] = value;
            var result = "";
            $.ajax({
                type: "post",
                url: JSUtility.url,
                data: $.toJSON(param),
                async: false,
                dataType: "json",
                success: function(data) {
                    result = data.flag;
                }
            });
            if (result == "False") {
                $.fn.validatebox.defaults.rules.projectNumAjax.message = '项目编号不存在';
                return false;
            }
            else {
                return true;
            }
        },
        message: ''
    },
    contractsNumAjax: {
        validator: function(value, params) {
            var param = { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ContractInfoPresenter", Method: "IsExit", Options: {} };
            param.Options["OuterNum"] = value;
            if (params != null && params != "undefined")
                param.Options["InternalType"] = params[0]; //工程,集成,科研 区分 默认工程
            else {
                param.Options["InternalType"] = "0";
            }
            var result = "";
            $.ajax({
                type: "post",
                url: JSUtility.url,
                data: $.toJSON(param),
                async: false,
                dataType: "json",
                success: function(data) {
                    result = data.flag;
                }
            });
            if (result == "False") {
                $.fn.validatebox.defaults.rules.projectNumAjax.message = '合同外部编号不存在';
                return false;
            }
            else {
                return true;
            }
        },
        message: ''
    },
    contractsNumAAjax: {
        validator: function(value, params) {
            var param = { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ContractAInfoPresenter", Method: "IsExit", Options: {} };
            param.Options["ContractNum"] = value;
            var result = "";
            $.ajax({
                type: "post",
                url: JSUtility.url,
                data: $.toJSON(param),
                async: false,
                dataType: "json",
                success: function(data) {
                    result = data.flag;
                }
            });
            if (result == "False") {
                $.fn.validatebox.defaults.rules.projectNumAjax.message = '甲方合同编号不存在';
                return false;
            }
            else {
                return true;
            }
        },
        message: ''
    }
});


JSHelper = {
    getIframeValue: function(iframe, name) {
        var ofrm1 = document.getElementById(iframe).document;
        if (ofrm1 == undefined) {
            ofrm1 = document.getElementById(iframe).contentWindow.document;
            var ff = ofrm1.getElementById(name).value;
            return ff;
        } else {
            var ie = document.frames[iframe].document.getElementById(name).value;
            return ie;
        }
    },
    getParentValue: function(name) {
        return window.parent.document.getElementById(name).value;
    }, //添加tab
    addTab: function(data, title, url, icon) {
        $(window.parent.document).find('#TabData').val(data);
        $(window.parent.document).find('#TabTitle').val(title);
        $(window.parent.document).find('#TabContent').val(url);
        $(window.parent.document).find('#TabIcon').val(icon);
        $(window.parent.document).find('#AddTab').click();
    }, //判断是否选中一行数据,返回选择数据
    isDatagridSelected: function(grid) {
        if (!grid) grid = $('#Grid');
        var data = grid.datagrid('getSelected');
        if (!data) {
            $.messager.alert('系统提示', '请选择一条记录', 'info');
            return null;
        }
        return data;
    },
    ajaxComboCheck: function(url, div, combo) {
        $('#' + combo).combo({
            required: true,
            editable: false
        });
        $("#" + combo).combo({ missingMessage: '该输入项为必输入项' });
        $.getJSON(url, function(data) {
            var input = "";
            $.each(data, function(i, n) {
                input += "<input type=\"checkbox\" id='" + n.text + "' class='easyui-validatebox'  value='" + n.id + "' /><span>" + n.text + "</span><br />";
            });
            $('#' + div + '').html(input);
            $('#' + div + '').appendTo($('#' + combo + '').combo('panel'));
            $('#' + div + '> input').bind("click", function() {
                var v = "", s = "";
                $('#' + combo + '').combo('setValue', s).combo('setText', s);
                $('#' + div + '> input:checked').each(function() {
                    // alert($(this).val());
                    if (v != "") {
                        v += ",";
                        s += ",";
                    }
                    v += $(this).val();
                    s += $(this).next('span').text();
                });
                $('#' + combo + '').combo('setValue', s).combo('setText', s);
            });
            $("#" + combo).focusout(function() {
                $('#' + combo + '').combo('hidePanel');
            });
        });
    },
    ajaxDataBindComboCheck: function(data, div, combo) {
        var array = data.split(',');
        //        if (array == 'undefined' || array == null)
        //            $("#" + div + "> input[id='" + data + "']").attr("checked", "checked");
        //        else if (array.length == 1)
        //            $("#" + div + "> input[id='" + array[0] + "']").attr("checked", "checked");
        //        else {
        $.each(array, function(i, n) {
            //$("#" + div + "> input[id='" + n + "']").attr("checked", true);
            $("#" + div + "> input[id='" + n + "']").click();
        });
        //};
        $("#" + combo).combo("setText", data).combo("setValue", data);
    },
    clearComboCheck: function(div, combo) {

        //        $("#" + div + "> input:checked").attr("checked", false);
        //        $("#" + div + "> input:checked").removeAttr("checked");
        $("#" + div + "> input:checked").click();
        $("#" + combo).combo("setText", "");
        $("#" + combo).combo("setValue", "");
    },
    comboCheckValue: function(div, combo) {
        var v = "", s = "";
        $('#' + div + '> input:checked').each(function() {
            // alert($(this).val());
            if (v != "") {
                v += ",";
                s += ",";
            }
            v += $(this).val();
            s += $(this).next('span').text();
            $('#' + combo + '').combo('setValue', s).combo('setText', s);
        });
        $('#' + combo + '').combo('hidePanel');
    },

    comboboxData: function(id, typeid) {
        var url = '../Handler/AjaxComboboxData.ashx?typeId=' + typeid + '';
        $(id).combobox({
            //项目级别
            url: url,
            valueField: 'text',
            textField: 'text'
        });
    },
    comboboxData2: function(id, typeid) {
        var url = '../../Handler/AjaxComboboxData.ashx?typeId=' + typeid + '';
        $(id).combobox({
            //项目级别
            url: url,
            valueField: 'text',
            textField: 'text'
        });
    },
    dataBindTree: function(id, val) {
        $(id).combotree("setValues", "");
        var children = $(id).combotree("tree").tree('getChildren');
        var values = val.split(",");
        for (var i = 0; i < children.length; i++) {
            for (var j = 0; j < values.length; j++) {
                if (values[j] == children[i].text) {
                    $(id).combotree("tree").tree("check", children[i].target);
                    break;
                }
            }
        }
    },
    projectNumColl: {},
    param: { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ProjectInfoPresenter", Method: "GetProjectNum", Options: {} },
    getProjectName: function(projectNum, rowData) {
        if (projectNumColl[projectNum] != null && projectNumColl[projectNum] != "undefined") {
            rowData.ProjectName = projectNumColl[projectNum];
            return;
        }
        JSHelper.param.Options["ProjectNum"] = ProjectNum;
        var result;
        $.ajax({
            type: "post",
            url: JSUtility.url,
            data: $.toJSON(JSHelper.param),
            async: true,
            dataType: "json",
            success: function(data) {
                JSUtility.grid.
                rowData.ProjectName = data.flag.ProjectName;
                projectNumColl[projectNum] = data.flag.ProjectName;
            }
        });
    },
    combotreeProject: function(comboId, url2, width) {
        if (width != null)
            $("#" + comboId).css("width", width + "px");
        else {
            $("#" + comboId).css("width", "205px");
        }
        $("#" + comboId).combotree({
            url: url2 == null ? "../Handler/AjaxProjectTreeHandle.ashx?internaltype=0" : url2
        });

        //$("#ProjectId").attr("validtype", "projectNumAjax[0]");  //validtype="projectNumAjax[0]"
        $("#" + comboId).combotree("tree").tree({
            onClick: function(node) {
                if (node.attributes == null || node.attributes == 'undefined') {
                    // $.messager.alert('系统提示', '此项不可选', 'info');
                    $("#" + comboId).combotree("setValue", null);
                    $("#" + comboId).combotree("setText", null);
                } else {
                    $("#" + comboId).combotree("setValue", node.attributes["ProjectNum"]);
                    $("#" + comboId).combotree("setText", node.text);
                    $("#" + comboId).combotree("hidePanel");
                }
            }
        });
    },
    conbotreeUpdateProject: function(comboId) {
        // $("#" + comboId).combotree({r });
        $("#" + comboId).combotree("setValue", JSUtility.row.ProjectId);
        $("#" + comboId).combotree("setText", JSUtility.row.ProjectName);
    }
};
JSUtility = {
    url: '../Handler/AjaxHandle.ashx',
    operate: null,
    row: null,
    window_edit: $("#Add"),
    window_edit_title: "",
    window_edit_form: $('#Add').find("form"),
    grid: null,
    param: { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ProjectPrizePresenter", Method: "", Options: {} },
    replenish: function() {
    }, //附加函数,在Add,Search清空表单内容后对需要赋值的文件进行操作函数
    saveReplenish: function() {
    }, //在添加,修改,查询数据时,参数赋值后需要值改变的操作函数
    add: function() {
        JSUtility.window_edit.window({ title: '添加' + JSUtility.window_edit_title, iconCls: 'icon-add', closed: false });

        JSUtility.window_edit_form.form("clear");
        JSUtility.operate = "add";
        JSUtility.replenish();
    },
    update: function() {
        JSUtility.row = JSHelper.isDatagridSelected($("#Grid"));
        if (JSUtility.row == null) return;
        JSUtility.window_edit_form.form("load", JSUtility.row);
        //alert(row.ProjectField.split(","));
        JSUtility.window_edit.window({ title: '修改' + JSUtility.window_edit_title, iconCls: 'icon-edit', closed: false });
        JSUtility.operate = "update";
    },
    search: function() {

        JSUtility.window_edit.window({ title: '查询' + JSUtility.window_edit_title, iconCls: 'icon-search', closed: false });

        JSUtility.window_edit_form.form("clear");
        JSUtility.operate = "Search";
        JSUtility.replenish();
    },
    save: function() {
    if (!JSUtility.window_edit_form.form("validate") && JSUtility.operate != "Search") return;
        var items = JSUtility.window_edit_form.serializeArray();
        $.each(items, function(i, item) {
            JSUtility.param.Options[item.name] = item.value;
        });
        JSUtility.saveReplenish();
        //alert($.toJSON(param.Options));
        if (JSUtility.operate == "add")
            JSUtility.param.Method = "Add";
        else if (JSUtility.operate == "update") {
            JSUtility.param.Method = "Update";
            JSUtility.param.Options["Id"] = JSUtility.row.Id;
        } 
        else if (JSUtility.operate == "Search") {
            JSUtility.window_edit.window("close");
            JSUtility.param.Method = "Search";
            JSUtility.grid.datagrid({ method: "post", queryParams: { "json": $.toJSON(JSUtility.param) }, url: JSUtility.url });
            JSUtility.grid.datagrid('options').pageNumber = 1;
            return;
        }
    $.ajax({
            type: "post",
            url: JSUtility.url,
            data: $.toJSON(JSUtility.param),
            dataType: "json",
            success: function(data) {
                if (data.flag) {
                    JSUtility.grid.datagrid('reload');
                    $.messager.show({ msg: data.msg, title: "info" });
                    JSUtility.window_edit.window('close');
                } else {
                    $.messager.alert('错误', data.msg, 'error');
                }
            }
        });
    },

    del: function() {
        JSUtility.row = JSHelper.isDatagridSelected($("#Grid"));
        if (JSUtility.row == null) return;
        $.messager.confirm("删除提示", "是否确认要删除该条信息?", function(b) {
            if (b) {
                JSUtility.param.Method = "Delete";
                JSUtility.param.Options["Id"] = JSUtility.row.Id;
                $.ajax({
                    type: "post",
                    url: JSUtility.url,
                    data: $.toJSON(JSUtility.param),
                    dataType: "json",
                    success: function(data) {
                        if (data.flag) {
                            JSUtility.grid.datagrid('reload');
                            $.messager.show({ msg: data.msg, title: "info" });
                            //$.messager.alert('提示', data.msg, 'info');
                        } else {
                            $.messager.alert('错误', data.msg, 'error');
                        }
                    }
                });
            }
        });
    },
    close: function() {
        JSUtility.window_edit.window('close');
        JSUtility.window_edit_form.form("clear");
    }
};
TreeUtility = {
    treeUrl: "",
    url: '../Handler/AjaxHandle.ashx',
    comboboxUrl: "",
    checkbox: true,
    operate: null,
    window_edit_form: $('#form_stage'),
    param: { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ProjectPrizePresenter", Method: "", Options: { } },
    window_tree: null,
    window_combobox: null,
    loadTree: function() {
        TreeUtility.window_tree.tree({
            checkbox: TreeUtility.checkbox,
            animate: true,
            url: TreeUtility.treeUrl,
            onSelect: function(node) {
                var id = node.id;
                TreeUtility.param.Options["ID"] = id;
                TreeUtility.param.Method = "Get";
                $.ajax({
                    type: "post",
                    url: TreeUtility.url,
                    data: $.toJSON(TreeUtility.param),
                    dataType: "json",
                    success: function(data) {
                        TreeUtility.window_edit_form.form("load", data);
                    }
                });
            },
            onExpand: function(node) {
            }
        });
    },
    comboboxInitial: function() {
        TreeUtility.window_combobox.combobox({
            url: TreeUtility.comboboxUrl,
            valueField: 'id',
            textField: 'text'
        });
    },
    add: function() {
        TreeUtility.param.Method = "Add";
        TreeUtility.save();
    },

    update: function() {
        var selected = TreeUtility.window_tree.tree("getSelected");
        if (selected == null) {
            $.messager.alert('提示', "请在左边选择一条数据", 'info');
            return;
        }
        if (selected.id == TreeUtility.window_combobox.combobox("getValue")) {
            TreeUtility.window_combobox.focus();
            $.messager.alert('提示', "不能选择本身做为父级!", 'info');
            return;
        }
        TreeUtility.param.Method = "Update";
        TreeUtility.param.Options["Id"] = selected.id;
        TreeUtility.save();
    },

    save: function() {
        if (!TreeUtility.window_edit_form.form("validate")) return;
        var items = TreeUtility.window_edit_form.serializeArray();
        $.each(items, function(i, item) {
            TreeUtility.param.Options[item.name] = item.value;
        });
        $.ajax({
            type: "post",
            url: TreeUtility.url,
            data: $.toJSON(TreeUtility.param),
            dataType: "json",
            success: function(data) {
                if (data.flag) {
                    TreeUtility.window_tree.tree('reload');
                    //TreeUtility.comboboxInitial();
                    TreeUtility.window_combobox.combotree("reload");
                    TreeUtility.window_edit_form.form('clear');
                    $.messager.show({ msg: data.msg, title: "info" });
                } else {
                    $.messager.alert('错误', data.msg, 'error');
                }
            }
        });
    },
    del: function() {
        var selected = TreeUtility.window_tree.tree("getSelected");
        if (!selected) {
            $.messager.alert('提示', "请在左边选择一条数据", 'info');
            return;
        }
        $.messager.confirm("删除提示", "是否确认要删除该条信息?", function(b) {
            if (b) {
                TreeUtility.param.Method = "Delete";
                TreeUtility.param.Options["Id"] = selected.id;
                $.ajax({
                    type: "post",
                    url: TreeUtility.url,
                    data: $.toJSON(TreeUtility.param),
                    dataType: "json",
                    success: function(data) {
                        if (data.flag) {
                            TreeUtility.window_tree.tree("reload");
                            TreeUtility.window_combobox.combotree("reload");
                            $.messager.show({ msg: data.msg, title: "info" });
                            //$.messager.alert('提示', data.msg, 'info');
                        } else {
                            $.messager.alert('错误', data.msg, 'error');
                        }
                    }
                });
            }
        });
    }
};
//权限处理
UserHandle = {
    ModuleAuthoritys: "", //模块权限
    UserModuleAuthoritys: "",
    /*初始化模块权限*/
    InitModule: function(moduleTag) {
        var param = { AssemblyName: "OA.Bll.Project", ClassName: "OA.Bll.Project.ProjectPrizePresenter", Method: "", Options: {} };
        param.Options["moduleTag"] = moduleTag;
        param.Options["Type"] = "Module"; //模块
        $.ajax({
            async: false,
            type: "post",
            dataType: "json",
            url: "../Handler/UserAuthorityHandler.ashx",
            data: $.toJSON(param),
            success: function(data) {
                UserHandle.ModuleAuthoritys = data;
                /**获取用户模块权限**/
                param.Options["Type"] = "UserAuthority";
                $.ajax({
                    async: false,
                    type: "post",
                    dataType: "json",
                    url: "../Handler/UserAuthorityHandler.ashx",
                    data: $.toJSON(param),
                    success: function(result) {
                        UserHandle.UserModuleAuthoritys = result;
                    },
                    error: function(xmlHttpRequest, textStatus, errorThrown) {
                        alert(xmlHttpRequest);
                    }
                });
            }
        });
    },
    /*验证操作权限*/
    /*operationName的值可以为BROWSE(浏览)、ADD(添加)、EDIT、DELETE、
    SEARCH、VERIFY(审核)、MOVE、PRINT(打印)、DOWNLOAD(下载)
    BACKUP(备份)、GRANT(授权)、VIEW(查看)*/
    ValidationHandle: function(operationName) {
        var bl = false;
        $.each(UserHandle.ModuleAuthoritys, function(name, value) {
            if (value.AuthorityTag.toString().toLowerCase() == operationName.toString().toLowerCase()) {
                $.each(UserHandle.UserModuleAuthoritys, function(i, n) {
                    if (n.AuthorityTag.toString().toLowerCase() == operationName.toString().toLowerCase()) {
                        bl = true;
                    }
                });
            }
        });
        return bl;
    }
};
